package visual;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TribeTreeVisual extends JFrame{

	public static void main(String[] args){
		new TribeTreeVisual();
	}
	
	public TribeTreeVisual(){
		_root = new DefaultMutableTreeNode();
		initGUI();
	}	
	
	JTree _tree;
	JScrollPane _treeView;
	JButton _loadData;
	DefaultMutableTreeNode _root;
	
	public void initGUI(){
		this.setBounds(100, 100, 450, 750);
		this.setVisible(true);
		getContentPane().setLayout(null);
		{
			_tree = new JTree(_root);		
			_tree.setBounds(0, 0, 400, 400);
			_tree.setVisible(true);
			getContentPane().add(_tree);			
		}
		{
			_treeView = new JScrollPane(_tree);
			_treeView.setVisible(true);
			_treeView.setBounds(20, 20, 400, 400);
			getContentPane().add(_treeView);
		}
		{
			_loadData = new  JButton("Load-Textfile");
			_loadData.setBounds(20, 420, 140, 30);
			_loadData.setVisible(true);
			_loadData.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					loadData();
				}
			});
			getContentPane().add(_loadData);
		}
		this.repaint(0, 0, getWidth(), getHeight());
	}

	private void resetTreeModel(){
		DefaultTreeModel treeModel = new DefaultTreeModel(_root);
		_tree.setModel(treeModel);
	}
	
	protected void loadData() {
		try {
			_root = new DefaultMutableTreeNode("Root");
			JFileChooser jfc = new JFileChooser();
			jfc.showOpenDialog(this);
			File f = jfc.getSelectedFile();
			FileInputStream fis;
		
			fis = new FileInputStream(f);
		
			Scanner s = new Scanner(fis);
			while(s.hasNext()){
				String next = s.next();
				_root.add(new DefaultMutableTreeNode(next));
			}
			resetTreeModel();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	
}
